import pgzrun
import random
import time
import json

name="./LifeGameMap1.json"
ftext=''
n=0
while not n:
    print("请输入文件编号")
    a=input()
    name="./LifeGameMap"+a+".json"
    try:
        with open(file = name, mode = 'r', encoding = 'utf8') as f:
            ftext = f.read()
        n=1
    except:
        continue

data = json.loads(ftext)

ROWS = data["size"][0]
COLS = data["size"][1]
CELL_SIZE = data["size"][2]

HEIGHT = (ROWS * CELL_SIZE)
WIDTH  = (COLS * CELL_SIZE)

BACK_COLOR = [0, 0, 127]

def GenCellColor():
    return [random.randint(0, 200), random.randint(0, 200), random.randint(0, 200)]

def init_map(rows, cols):
    return [[[0, BACK_COLOR] for c in range(cols)] for r in range(rows)]

world = init_map(ROWS, COLS)
next_world = init_map(ROWS, COLS)

def do_map(w):
    for i in data['map']:
        w[i[0]][i[1]] = [1, GenCellColor()]

def draw_cell(w, r, c):
    cx = CELL_SIZE * c
    cy = CELL_SIZE * r
    cell_rect = Rect((cx, cy), (CELL_SIZE, CELL_SIZE))
    screen.draw.filled_rect(cell_rect, tuple(w[r][c][1]))

def count_neighbors(w, r, c):
    sum = 0
    clr = [0, 0, 0]
    for nr in range(r - 1, r + 1 + 1):
        for nc in range(c - 1, c + 1 + 1):
            mr=nr
            mc=nc
            
            if nr == r and nc == c:
                continue
            
            if nr < 0:
                mr = ROWS-1
            if nr >= ROWS:
                mr = 0
            
            if nc < 0:
                mc = COLS-1
            if nc >= COLS:
                mc = 0

            if w[mr][mc][0]:
                sum += 1
                clr[0] += w[mr][mc][1][0]
                clr[1] += w[mr][mc][1][1]
                clr[2] += w[mr][mc][1][2]
    if sum == 0:
        return sum, clr
    else:
        return sum, [clr[0] // sum, clr[1] // sum, clr[2] // sum]

def next_cell(w, r, c):
    n, clr = count_neighbors(w, r, c)

    if n == 3:
        return [1, clr]
    elif n == 2:
        return w[r][c]
    else:
        return [0, BACK_COLOR]

def update():
    for r in range(ROWS):
        for c in range(COLS):
            next_world[r][c] = next_cell(world, r, c)
    
    for r in range(ROWS):
        for c in range(COLS):
            world[r][c] = next_world[r][c]
            
#    time.sleep(0.1)

def draw():
    screen.fill(tuple(BACK_COLOR))
    for r in range(ROWS):
        for c in range(COLS):
            if world[r][c][0]:
                draw_cell(world, r, c)

do_map(world)

pgzrun.go()